/**
 * 文件相关接口
 */
// import FileSaver from 'file-saver';
import http, { BASE_NAME } from './index';

export const apiBasePath_system_file = `${BASE_NAME}/api/file`;

/**
 * 上传文件 -> 多个文件
 */
export const apiPath_fireUpload = `${apiBasePath_system_file}/multiUpload`;

export const fileMultiUpload = async (data) => {
  const formData = new FormData();

  for (const [key, value] of Object.entries(data)) {
    if (key === 'files') {
      for (let i = 0; i < value?.length; i++) {
        formData.append(key, value[i]);
      }
    } else {
      formData.append(key, value);
    }
  }

  try {
    const response = await http.post(apiPath_fireUpload, formData);

    return [null, response];
  } catch (e) {
    return [(typeof e === 'string' && e) || 'error', null];
  }
};

/**
 * 上传多张图片并生成缩略图
 */
export const apiPath_imageUpload = `${apiBasePath_system_file}/uploadImages`;

export const imageMultiUpload = async (data) => {
  const formData = new FormData();

  for (const [key, value] of Object.entries(data)) {
    if (key === 'files') {
      for (let i = 0; i < value?.length; i++) {
        formData.append(key, value[i]);
      }
    } else {
      formData.append(key, value);
    }
  }

  try {
    const response = await http.post(apiPath_imageUpload, formData);

    return [null, response];
  } catch (e) {
    return [(typeof e === 'string' && e) || 'error', null];
  }
};

/**
 * 删除文件 -> 多个文件
 */
export const apiPath_fireDel = `${apiBasePath_system_file}/delete`;

export async function fireDel(data) {
  try {
    const response = await http.delete(`${apiPath_fireDel}?fileIds=${data}`);

    return [null, response];
  } catch (e) {
    return [(typeof e === 'string' && e) || 'error', null];
  }
}

/**
 * 下载文件
 */
export const fileDownload = async (fileId) => {
  try {
    const response = await http.post(`${apiBasePath_system_file}/download/${fileId}`);

    // FileSaver.saveAs(
    //   new Blob([response], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' }),
    //   '',
    // );

    return [null, response];
  } catch (e) {
    return [(typeof e === 'string' && e) || 'error', null];
  }
};
